from flask import Blueprint, request, jsonify
from services.k8s_service import update_k8s_image, update_k8s_image_form, rollback_deployment

k8s_bp = Blueprint('k8s', __name__)


@k8s_bp.route('/update_image', methods=['POST'])
def update_image():
    """处理JSON格式的镜像更新请求"""
    return update_k8s_image()


@k8s_bp.route('/update_image2', methods=['POST'])
def update_image2():
    """处理表单格式的镜像更新请求"""
    return update_k8s_image_form()


@k8s_bp.route('/rollback', methods=['POST'])
def rollback():
    """
    处理回滚请求
    """
    data = request.get_json()

    # 参数校验
    if not all(key in data for key in ['namespace', 'deployment']):
        return jsonify({'error': 'Missing required parameters (namespace, deployment)'}), 400

    # 执行回滚
    success, message = rollback_deployment(
        namespace=data['namespace'],
        deployment_name=data['deployment'],
        revision=data.get('revision')
    )

    return jsonify({'message': message}) if success else jsonify({'error': message}), 200 if success else 400
